<?php

namespace App\Http\Controllers\CRM;

use App\Enums\MemberStatus;
use App\Enums\OrderItemType;
use App\Enums\TradeStatus;
use App\Helper\ApiResponseHelper;
use App\Http\Controllers\Controller;
use App\Models\Member;
use App\Models\Order;
use App\Models\Store;
use Illuminate\Http\Request;

class StoreMemberController extends Controller
{
    public function getMemberList(Store $store)
    {
        $orders = Order::where('store_id', $store->id)
            ->where('status', TradeStatus::Created)
            ->whereNotNull('member_id')
            ->with('member')
            ->get();

        $memberList = [];
        /**
         * @var Order $order
         */
        foreach ($orders as $order) {

            $member = $order->member;
            $isAssistant = $order->items()->where('type', OrderItemType::Assistant)->exists();
            $status = $isAssistant ? MemberStatus::Assistant : MemberStatus::NotAssistant;

            $memberList[] = [
                'member' => $member,
                'status' => $status,
                'status_label' => $status->label()
            ];
        }

        return ApiResponseHelper::json($memberList);
    }

    public function getMemberInfo(Store $store, Member $member)
    {
        /**
         * @var Order $order
         */
        $order = Order::where('store_id', $store->id)
            ->where('member_id', $member->id)
            ->where('status', TradeStatus::Created)
            ->with('items')
            ->first();

        $tableItem = $order->getTableItem();
        $endAt = date('Y-m-d H:i:s');
        $tableMinutes = $tableItem->getTotalMinutes($endAt);

        $assistantItems = $order->items()->where('type', OrderItemType::Assistant)->with('assistantUser')->get();
        $assistantMoney = 0;
        $assistantList = [];
        foreach ($assistantItems as $item) {

            $assistantMoney += $item->money;
            $_endAt = $item->end_at;
            if (empty($_endAt))
                $_endAt = $endAt;
            $minutes = $item->getTotalMinutes($_endAt);
            $startAt = $item->start_at;

            $assistantList[] = [
                'assistant' => $item->assistantUser,
                'minutes' => $minutes,
                'money' => $item->money,
                'start_at' => $startAt,
                'end_at' => $_endAt,
            ];
        }

        return ApiResponseHelper::json([
            'member' => $member,
            'order' => $order,
            'table' => [
                'table' => $tableItem->table,
                'minutes' => $tableMinutes,
                'money' => $tableItem->table->getTablePrice($endAt),
            ],
            'goods' => [
                'money' => $order->items()->where('type', OrderItemType::Goods)->sum('money'),
            ],
            'assistant' => [
                'money' => $assistantMoney,
                'list' => $assistantList
            ]
        ]);
    }
}
